#!/bin/bash
set -o errexit

LAST_DIR=$(pwd)
CUR_DIR=$(cd "$(dirname "$0")"; pwd)
cd ${CUR_DIR}

# 执行程序的用户
DAEMON_USER=root

# 实例名称
DAEMON_NAME=$(basename $(ls daemon/*.war))
DAEMON_NAME=${DAEMON_NAME%*.war}

# 实例基础路径
DAEMON_BASE=/opt/${DAEMON_NAME}

DAEMON_SHELL=${DAEMON_BASE}/${DAEMON_NAME}.war

# 日志目录
DAEMON_LOG=/data/log/${DAEMON_NAME}

if [ $USER != "root" ]; then
	sudo ./install.bash
	exit
fi

echo "检测服务运行状态"
if [ -x /etc/init.d/${DAEMON_NAME} ]; then
	echo "正在停止服务"
	service ${DAEMON_NAME} stop
	echo "服务已停止"
else
	echo "服务未运行"
fi

echo "删除原有程序目录"
rm -fr ${DAEMON_BASE}

echo "创建程序目录并拷贝文件"
mkdir -p ${DAEMON_BASE}
cp -r ./daemon/* ${DAEMON_BASE}/

echo "检查并创建日志路径"
if [ -d ${DAEMON_LOG} ]; then
	echo "日志目录已存在"
else
	mkdir -p ${DAEMON_LOG}
fi
ln -s ${DAEMON_LOG} ${DAEMON_BASE}/logs
echo "日志软连接已创建"

echo "设置脚本及目录的权限"
chmod +x ${DAEMON_SHELL}
chown ${DAEMON_USER} ${DAEMON_LOG}
chown ${DAEMON_USER} -R ${DAEMON_BASE}

echo "设置系统服务"
rm -f /etc/init.d/${DAEMON_NAME}
ln -s ${DAEMON_SHELL}  /etc/init.d/${DAEMON_NAME}

echo "开机不自启动"
update-rc.d -f ${DAEMON_NAME} remove
# update-rc.d ${DAEMON_NAME} defaults

# echo "启动服务"
# service ${DAEMON_NAME} start

echo -e "\n\n安装完成。\n\n"
echo -e "请使用以下命令启动服务：\nsudo service ${DAEMON_NAME} start\n日志目录为：\n/opt/${DAEMON_NAME}/logs\n\n"
